package com.zq.it.service.impl.exam;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import com.zq.it.dao.common.PageConfig;
import com.zq.it.pojo.Teacher;
import com.zq.it.pojo.exam.TOptions;
import com.zq.it.pojo.exam.TQuestionDb;
import com.zq.it.pojo.exam.TQuestions;
import com.zq.it.pojo.exam.data.ObjectData;
import com.zq.it.service.common.BaseServiceImpl;
import com.zq.it.service.exam.QuestionService;
import com.zq.it.service.validate.VolidateException;
import com.zq.it.tool.Constant;
import com.zq.it.tool.Html2Text;
import com.zq.it.tool.StringUtil;

import net.sf.json.JSONArray;

/**
 * Question的service接口实现类
 *
 * @author 王凡
 *
 * @version $ID: QuestionServiceImpl.java 2013-8-7 王凡@$
 */

public class QuestionServiceImpl extends BaseServiceImpl
		implements
			QuestionService {

	@Override
	public ObjectData getQuestionDBList(PageConfig config) {
		ObjectData data = null;
		data = getListByPage(config);
		List<TQuestionDb> list = data.getList();
		if (null != list) {
			for (TQuestionDb qdb : list) {
				qdb.setTeacher(
						getTeacherDao().findById(qdb.getTeacher().getId()));
			}
		}
		return data;
	}

	@Override
	public void addQDB(TQuestionDb qdb) {
		questionDbDAO.save(qdb);
	}

	@Override
	public String deleteQDB(String[] ids, Teacher teacher) {
		TQuestionDb qdb = null;
		List temp;
		try {
			for (String id : ids) {
				qdb = questionDbDAO.findById(Long.parseLong(id));
				if (qdb.getTeacher().getId() == teacher.getId()) {
					temp = questionsDAO.findByHql("from TQuestions t where t.TQuestionDb.id=" + id);
					if (null != temp && temp.size() > 0)
						return "false";
					questionDbDAO.delete(qdb);
				}
			}
			return "ok";
		} catch (Exception e) {
			return "false";
		}
	}

	@Override
	public TQuestionDb getQDBById(String id) {
		TQuestionDb qdb = questionDbDAO.findById(Long.parseLong(id));
		qdb.setTeacher(getTeacherDao().findById(qdb.getTeacher().getId()));
		return qdb;
	}

	@Override
	public void updateQDB(Teacher teacher, TQuestionDb qdb) throws Exception {
		TQuestionDb data = questionDbDAO.findById(qdb.getId());
		if (data.getTeacher().getId() == teacher.getId()) {
			data.setDbName(qdb.getDbName());
			questionDbDAO.update(data);
		} else {
			throw new Exception();
		}
	}

	@Override
	public String creatQDBHql(Teacher teacher, TQuestionDb qdb) {
		StringBuffer hql = new StringBuffer(
				"from TQuestionDb as model where 1=1");
		String nameSql = null == qdb.getDbName() || "".equals(qdb.getDbName())
				? ""
				: " and model.dbName like '%" + qdb.getDbName() + "%'";
		String createrSql = " and model.Teacher.id = " + teacher.getId();
		hql.append(nameSql).append(createrSql);
		return hql.toString();
	}

	@Override
	public ObjectData getQuestionList(PageConfig config) {
		ObjectData data = getListByPage(config);
		List<TQuestions> list = data.getList();
		if (null != list) {
			for (TQuestions question : list) {
				question.setTeacher(getTeacherDao()
						.findById(question.getTeacher().getId()));
				question.setTQuestionDb(questionDbDAO
						.findById(question.getTQuestionDb().getId()));
			}
		}
		return data;
	}

	@Override
	public boolean addQuestion(TQuestions question, String skey,
			String[] soption, String qcomplex, Teacher teacher,
			HttpServletRequest request) {
		boolean flag = false;
		try {
			if (validate.validate(question)) {
				TQuestionDb qdb = questionDbDAO
						.findById(question.getTQuestionDb().getId());
				if (null != qdb) {
					question.setTeacher(teacher);
					question.setPostDate(new Date());
					switch (question.getQType()) {
						case Constant.QTYPE_SELECT :
							question.setSkey(skey);
							questionsDAO.save(question);
							TOptions option = null;
							String optionValue = null;
							for (int i = 1; i <= soption.length; i++) {
								optionValue = soption[i - 1];
								option = new TOptions(question, optionValue, i);
								optionsDAO.save(option);
							}
							break;
						case Constant.QTYPE_BLANK :
							JSONArray jsonArray = null;
							List ls = new ArrayList();
							Pattern p = Pattern.compile("\\[BlankArea.+?]");
							Matcher m = null;
							m = p.matcher(question.getContent());
							while (m.find()) {
								String blank = m.group();
								String blankid = blank.replace("BlankArea", "")
										.replaceAll("\\]", "");
								blankid = blankid.substring(1);
								Map _map = new HashMap();
								_map.put("ID", blankid);
								_map.put("VAL", StringUtil.trim(request
										.getParameter("skey" + blankid)));
								ls.add(_map);
							}
							Object cmap = new HashMap();
							qcomplex = request.getParameter("qcomplex");
							if ("yes".equals(qcomplex))
								((Map) cmap).put("QCOMPLEX", "YES");
							else {
								((Map) cmap).put("QCOMPLEX", "NO");
							}
							ls.add(cmap);
							jsonArray = JSONArray.fromObject(ls);
							question.setSkey(jsonArray.toString());
							questionsDAO.save(question);
							break;
						default :
							question.setSkey(skey);
							questionsDAO.save(question);
							break;
					}
					flag = true;
				} else {
					flag = false;
				}
			}
		} catch (VolidateException e) {
			flag = false;
		}
		return flag;
	}

	@Override
	public List getQuestionDBList(Teacher teacher) {
		return questionDbDAO
				.findByHql("from TQuestionDb as db where db.Teacher.id ="
						+ teacher.getId());
	}

	@Override
	public String creatQuestionHql(Teacher teacher, TQuestions question) {
		StringBuffer hql = new StringBuffer(
				"from TQuestions as model where 1=1");
		String contentSql = null == question.getContent()|| "".equals(question.getContent())
						? ""
						: " and model.content like '%" + question.getContent()
								+ "%'";
		String qTypeSql = question.getQType() < 0
				? ""
				: " and model.QType =" + question.getQType();
		String t_idSql = "and model.Teacher.id = '" + teacher.getId() + "'";
		String db_idSql = null == question.getTQuestionDb().getDbName()
				? ""
				: " and model.TQuestionDb.dbName like '%"
						+ question.getTQuestionDb().getDbName() + "%' ";
		hql.append(contentSql).append(qTypeSql)
				.append(t_idSql).append(db_idSql);
		return hql.toString();
	}

	@Override
	public TQuestions getQuestionById(String id, Teacher teacher) {
		TQuestions question = questionsDAO.findById(Long.parseLong(id));
		if (question.getTeacher().getId() == teacher.getId()) {
			question.setTQuestionDb(
					questionDbDAO.findById(question.getTQuestionDb().getId()));
			return question;
		}
		return null;
	}

	@Override
	public String[] getOptions(long id) {
		List<TOptions> list = optionsDAO
				.findByHql("from TOptions t where t.TQuestions.id = " + id
						+ " order by t.OId");
		String[] data = new String[list.size()];
		TOptions option;
		if (null != optionsDAO) {
			for (int i = 0; i < list.size(); i++) {
				option = list.get(i);
				data[i] = option.getSoption();
			}
		}
		return data;
	}

	@Override
	public String deleteQuestion(String[] ids, Teacher teacher) {
		TQuestions question = null;
		try {
			List temp;
			for (String id : ids) {
				question = questionsDAO.findById(Long.parseLong(id));
				if (question.getTeacher().getId() == teacher.getId()) {
					temp = paperDetailDAO.findByHql(
							"from TPaperDetail t where t.TQuestions.id = "
									+ id);
					if (null != temp && temp.size() > 0)
						return "false";
					optionsDAO.delByHql(
							"delete from TOptions t where t.TQuestions.id="
									+ id);
					questionsDAO.delete(question);
				}
			}
			return "ok";
		} catch (Exception e) {
			return "false";
		}
	}

	@Override
	public List getOptionsList(long id) {
		List<TOptions> data = optionsDAO
				.findByHql("from TOptions t where t.TQuestions.id = " + id
						+ " order by t.OId");
		return data;
	}

	@Override
	public ObjectData getQuestionList2Text(PageConfig config) {
		ObjectData data = getListByPage(config);
		List<TQuestions> list = data.getList();

		if (null != list) {
			for (TQuestions question : list) {
				question.setTeacher(getTeacherDao()
						.findById(question.getTeacher().getId()));
				question.setTQuestionDb(questionDbDAO
						.findById(question.getTQuestionDb().getId()));
				question.setContent(
						Html2Text.Html2TextFormate(question.getContent()));
			}
		}
		return data;
	}

}
